<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="dialogFormVisible"
    width="500px"
    @close="close"
  >
    <el-form ref="form" label-width="100px" :model="form" :rules="rules">
      <el-form-item label="角色名称" prop="name">
        <el-input disabled :value="form.name" />
      </el-form-item>
      <el-form-item label="权限">
        <div ref="treeBox" style="max-height: 300px; overflow: auto">
          <el-tree
            ref="tree"
            :data="resList"
            :default-checked-keys="defaultKeys"
            multiple
            node-key="id"
            :props="defaultProps"
            show-checkbox
          />
        </div>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button :loading="isSaving" type="primary" @click="save">
        确 定
      </el-button>
    </template>
  </el-dialog>
</template>

<script>
  import {
    queryListByRoleId,
    getFlatList,
    assignResource,
  } from '@/api/resource'
  import { Loading } from 'element-ui'

  export default {
    name: 'PermissionEdit',
    data() {
      return {
        defaultProps: {
          label: 'label',
          children: 'children',
        },
        cacheResList: [],
        resList: [],
        form: {},
        rules: {},
        title: '',
        dialogFormVisible: false,
        isSaving: false,
        defaultKeys: [],
        isLoading: false,
      }
    },
    created() {
      this.getTreeData()
    },
    methods: {
      // 加载角色树形控件数据
      getTreeData() {
        getFlatList()
          .then((res) => {
            if (res.status === 0 && Array.isArray(res.data)) {
              const arrBox = []
              const rootList = this.findRootReslist(res.data)
              for (const item of rootList) {
                const data = {
                  label: item.name,
                  id: item.id,
                }
                const temp = this.findSubReslist(res.data, item.id)
                if (temp.length > 0) {
                  data.children = temp
                }
                arrBox.push(data)
              }
              this.cacheResList = arrBox
              this.resList = arrBox
            } else {
              this.$baseMessage(
                '获取权限列表失败,[' + res.status + '][' + res.msg + ']',
                'error',
                'vab-hey-message-error'
              )
            }
          })
          .catch((e) => {
            console.log(e)
          })
      },
      getData(row) {
        this.form.roleId = row.id
        this.form.name = row.name
        this.isLoading = true
        const loadingInstance = Loading.service({ target: this.$refs.treeBox })
        queryListByRoleId(row.id)
          .then((res) => {
            if (res && res.status === 0) {
              const arrBox = []
              for (const item of res.data) {
                arrBox.push(item.id)
              }
              this.defaultKeys = arrBox
            } else {
              this.$baseMessage(
                '获取角色资源失败,[' + res.status + '][' + res.msg + ']',
                'error',
                'vab-hey-message-error'
              )
            }
            loadingInstance.close()
          })
          .catch((e) => {
            console.log(e)
            loadingInstance.close()
          })
      },
      // 查找根权限
      findRootReslist(list) {
        const tempList = []
        for (const item of list) {
          if (item.pid === 0) {
            tempList.push(item)
          }
        }
        return tempList
      },
      // 递归加载子组件
      findSubReslist(list, pid) {
        const arrBox = []
        // console.log(list, pid)
        for (const item of list) {
          // console.log(item)
          if (item.pid !== pid) {
            continue
          }
          const data = {
            label: item.name,
            id: item.id,
          }
          const temp = this.findSubReslist(list, item.id)
          if (temp.length > 0) {
            data.children = temp
          }
          arrBox.push(data)
        }
        return arrBox
      },
      showEdit(row) {
        this.title = '分配权限'
        // this.form = Object.assign({}, row)
        this.getData(row)
        this.dialogFormVisible = true
      },
      close() {
        this.$refs['form'].resetFields()
        this.form = this.$options.data().form
        this.dialogFormVisible = false
        this.$refs.tree.setCheckedKeys([])
      },
      async save() {
        const treeKeys = this.$refs.tree
          .getCheckedNodes(false, true)
          .map((it) => {
            return it['id']
          })
        if (treeKeys.length === 0) {
          this.$baseMessage(
            '请选则要分配的权限！',
            'error',
            'vab-hey-message-error'
          )
          return
        }
        try {
          this.isSaving = true
          let res = await assignResource({
            roleId: this.form.roleId,
            resList: treeKeys,
          })
          let successMsg = '分配成功'
          let errorMsg = '分配失败'
          if (res && res.status === 0) {
            this.$baseMessage(
              res ? res.msg : successMsg,
              'success',
              'vab-hey-message-success'
            )
            this.$emit('fetch-data')
            this.close()
          } else {
            this.$baseMessage(
              res ? res.msg : errorMsg,
              'error',
              'vab-hey-message-error'
            )
          }
        } catch (e) {
          console.log(e)
          this.$baseMessage(
            e ? e.message : '操作失败',
            'error',
            'vab-hey-message-error'
          )
        }
        this.isSaving = false
      },
    },
  }
</script>
